package com.kaili.basic.util;

import com.kaili.basic.pojo.entity.MdmApkInfo;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @Desc: 获取apk图标工具类
 * @author: chenmengming
 * @Time: 2019/8/8 9:38
 * @Copyright: © 2019 杭州凯立通信有限公司 版权所有
 * @Warning: 本内容仅限于公司内部传阅, 禁止外泄或用于其它商业目的
 */
public class IconUtil {
    /**
     * 从指定的apk文件里获取指定file的流
     *
     * @param apkpath
     * @param fileName
     * @return
     */
    public static InputStream extractFileFromApk(String apkpath, String fileName) {
        try {
            ZipFile zFile = new ZipFile(apkpath);
            ZipEntry entry = zFile.getEntry(fileName);
            entry.getComment();
            entry.getCompressedSize();
            entry.getCrc();
            entry.isDirectory();
            entry.getSize();
            entry.getMethod();
            InputStream stream = zFile.getInputStream(entry);
            return stream;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void extractFileFromApk(String apkpath, String fileName, String outputPath) throws Exception {
        InputStream is = extractFileFromApk(apkpath, fileName);

        File file = new File(outputPath);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file), 1024);
        byte[] b = new byte[1024];
        BufferedInputStream bis = new BufferedInputStream(is, 1024);
        while (bis.read(b) != -1) {
            bos.write(b);
        }
        bos.flush();
        is.close();
        bis.close();
        bos.close();
    }

    /**
     * demo 获取apk文件的icon并写入磁盘指定位置
     *
     * @param args
     */
    public static void main(String[] args) {
        try {
            String apkpath = "D:\\apk文件\\快牙.apk";
            if (args.length > 0) {
                apkpath = args[0];
            }
            MdmApkInfo apkInfo = new ApkUtil().getApkInfo(apkpath);
            extractFileFromApk(apkpath, apkInfo.getApplicationIcon(), "D:\\apk文件图标\\icon.png");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}